
using Yarp.ReverseProxy.Forwarder;
using Yarp.ReverseProxy.Transforms;
using Yarp.ReverseProxy.Transforms.Builder;

namespace LyxWaf.Transformer
{

    // 1. 创建自定义请求转换器
    public class DestinationTrans : ITransformProvider
    {
        public void ValidateRoute(TransformRouteValidationContext context)
        {
            // Check all routes for a custom property and validate the associated
            // transform data
            if (context.Route.Metadata?.TryGetValue("CustomMetadata", out var value) ??
                false)
            {
                if (string.IsNullOrEmpty(value))
                {
                    context.Errors.Add(new ArgumentException(
                        "A non-empty CustomMetadata value is required"));
                }
            }
        }

        public void ValidateCluster(TransformClusterValidationContext context)
        {
            // Check all clusters for a custom property and validate the associated
            // transform data.
            if (context.Cluster.Metadata?.TryGetValue("CustomMetadata", out var value)
                ?? false)
            {
                if (string.IsNullOrEmpty(value))
                {
                    context.Errors.Add(new ArgumentException(
                        "A non-empty CustomMetadata value is required"));
                }
            }
        }

        public void Apply(TransformBuilderContext transformBuildContext)
        {
            transformBuildContext.AddRequestTransform(async transformContext =>
            {
                transformContext.HttpContext.Items.Add("ProxyDestUrl", transformContext.DestinationPrefix);
            });
            transformBuildContext.AddResponseTransform(async transformContext =>
            {
                transformContext.HttpContext.Response.Headers.Server = "LyxWaf";
            });

        }
    }

}